package com.niannian.service;

import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONObject;
import com.niannian.activity.FamilyNewsActivity;
import com.niannian.activity.MyActivity;
import com.niannian.activity.NewssActivity;
import com.niannian.activity.RegardsActivity;
import com.niannian.util.ErrorCode;
import com.niannian.util.MessageRecieveManager;
import com.niannian.web.nnSyncApi;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

/**
 * 轮旋拉取新增加的动态
 * 
 * @author shenglin
 * 
 */
public class MessageService extends Service {
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		starPlayStatusTimer();
		return Service.START_STICKY_COMPATIBILITY;
	}

	/*******************************************************
	 * 通过定时器轮旋拉取新增加的动态
	 ******************************************************/

	Timer timer;

	private void starPlayStatusTimer() {
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		TimerTask task = new TimerTask() {
			public void run() {
				try {
					if (FamilyNewsActivity.isForeground || NewssActivity.isForeground || MyActivity.isForeground) {
						getData();
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		};

		timer = new Timer(true);
		timer.schedule(task, 0, 10000);// 10秒拉取一次
	}

	public void getData() {
		new Thread() {
			@Override
			public void run() {
				try {
					String jsonStr = nnSyncApi.getFamilyNewsPostCount();
					JSONObject headJson = new JSONObject(jsonStr);
					int code = headJson.getInt("code");
					if (code == ErrorCode.OK) {
						MessageRecieveManager.FAMILY_NEWS_UPDATE_NUM = headJson.getInt("pc");
						MessageRecieveManager.GREETING_NEWS_UPDATE_NUM = headJson.getInt("rc");
						MessageRecieveManager.NEWS_UPDATE__NUM = headJson.getInt("rel_msg_c");

						if (MessageRecieveManager.FAMILY_NEWS_UPDATE_NUM > 0) {
							MessageService.this.sendBroadcast(new Intent(MessageRecieveManager.FAMILY_NEWS_UPDATE_ACTION));
						}
						if (MessageRecieveManager.GREETING_NEWS_UPDATE_NUM > 0) {
							MessageService.this.sendBroadcast(new Intent(MessageRecieveManager.GREETING_NEWS_UPDATE_ACTION));
						}
						if (MessageRecieveManager.NEWS_UPDATE__NUM > 0) {
							MessageService.this.sendBroadcast(new Intent(MessageRecieveManager.NEWS_UPDATE_ACTION));
						}
					} else {
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

}
